package com.dhwl.hsh.merchant.presenter;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.dhwl.hsh.lib.bean.HttpResponse;
import com.dhwl.hsh.lib.bean.resp.MerchantResp;
import com.dhwl.hsh.lib.core.HshException;
import com.dhwl.hsh.lib.core.mvp.BasePresenter;
import com.dhwl.hsh.lib.utils.ReservoirUtils;
import com.dhwl.hsh.lib.utils.ToastUtils;
import com.dhwl.hsh.merchant.HshApplication;
import com.dhwl.hsh.merchant.R;
import com.dhwl.hsh.merchant.model.impl.UserModel;
import com.dhwl.hsh.merchant.presenter.iview.IUserView;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 简要描述
 *
 * @author Derek.Kidd
 * @version V1.0.0
 * @date 2016-04-13 12:55
 */
public class UserPresenter extends BasePresenter<IUserView> {

    private ReservoirUtils reservoirUtils;

    public UserPresenter() {
        this.reservoirUtils = new ReservoirUtils();
    }


    public void getMerchant() {
        Subscriber<HttpResponse<MerchantResp>> subscriber = new Subscriber<HttpResponse<MerchantResp>>() {
            @Override
            public void onCompleted() {
                if (UserPresenter.this.mCompositeSubscription != null)
                    UserPresenter.this.mCompositeSubscription.remove(this);
            }

            @Override
            public void onError(Throwable e) {
                Log.e("getMerchant", e.getMessage());
                ToastUtils.show(HshApplication.mContext, R.string.network_not_exist, Toast.LENGTH_SHORT);

                HshException exception = new HshException(e.hashCode(), e.getMessage());
                UserPresenter.this.getMvpView().onUserFailure(exception);
            }

            @Override
            public void onNext(HttpResponse<MerchantResp> response) {

                if (response.getStatus() != 0) {
                    ToastUtils.show((Context) getMvpView(), response.getDescribe(), Toast.LENGTH_LONG);
                    HshException exception = new HshException(response.getStatus(), response.getDescribe());
                    UserPresenter.this.getMvpView().onUserFailure(exception);
                } else {

                    MerchantResp merchantResp = response.getData();
                    reservoirUtils.refresh("merchant_info", merchantResp);
                    UserPresenter.this.getMvpView().onUserSuccess(merchantResp);

                }
            }
        };
        this.mCompositeSubscription.add(UserModel.getInstance().getMerchant().subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber));
//
//        this.mCompositeSubscription.add(CommonModel.getInstance().getHtmlUrl().subscribeOn(Schedulers.io()).
//                observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber));
    }
}
